﻿@@master_page.html
<link href="css/page_table_list.css" rel="stylesheet" />
<script src="js/ace/src-min/ace.js"></script>
<script src="js/ace/src-min/ext-language_tools.js"></script>
<style>
    #divGroupedItems {
        max-height: 300px; /* 限制高度，启用滚动条 */
        overflow-y: auto; /* 垂直滚动条 */
        padding: 10px;
        border: 1px solid #ddd; /* 边框颜色 */
        border-radius: 5px; /* 圆角 */
        background-color: #f9f9f9; /* 背景色 */
    }

        #divGroupedItems .permission-group {
            margin-bottom: 10px; /* 分组间距 */ 
        }

            #divGroupedItems .permission-group label {
                font-size: 14px; /* 字体大小 */
                font-weight: 500; /* 字体权重 */
                color: #333; /* 字体颜色 */
                display: block; /* 独占一行 */
                margin-bottom: 5px; /* 标签与内容间距 */
                text-align:left
            }

        #divGroupedItems .permission-items {
            display: flex;
            flex-wrap: wrap; /* 多行排列 */
            gap: 8px; /* 项目间距 */
        }

            #divGroupedItems .permission-items label {
                font-size: 12px; /* 字体大小 */
                color: #555; /* 字体颜色 */
                background-color: #fff; /* 背景色 */
                border: 1px solid #ddd; /* 边框颜色 */
                border-radius: 3px; /* 圆角 */
                padding: 4px 8px; /* 内边距 */
                cursor: pointer; /* 鼠标样式 */
                transition: background-color 0.3s ease; /* 动画效果 */
            }

                #divGroupedItems .permission-items label:hover {
                    background-color: #f0f0f0; /* 悬停背景色 */
                }

            #divGroupedItems .permission-items input[type="checkbox"] {
                margin-right: 5px; /* 复选框与文字间距 */
            }

    .selected-users {
        display: flex;
        flex-wrap: wrap;
        gap: 8px; /* 卡片间距 */
        padding: 8px;
        border: 1px solid #ddd; /* 边框颜色 */
        border-radius: 5px; /* 圆角 */
        background-color: #f9f9f9; /* 背景色 */
    }

        .selected-users .user-badge {
            display: inline-flex;
            align-items: center;
            background-color: #e6f7ff; /* 卡片背景色 */
            color: #1890ff; /* 字体颜色 */
            padding: 4px 8px;
            border-radius: 12px; /* 圆角 */
            font-size: 12px;
            font-weight: 500;
            border: 1px solid #91d5ff; /* 卡片边框 */
            transition: all 0.3s ease; /* 动画效果 */
        }

            .selected-users .user-badge button {
                margin-left: 6px;
                background-color: #ff7875; /* 删除按钮背景色 */
                color: white;
                border: none;
                border-radius: 50%;
                width: 20px;
                height: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                cursor: pointer;
                transition: background-color 0.3s ease; /* 动画效果 */
            }

                .selected-users .user-badge button:hover {
                    background-color: #d9363e; /* 删除按钮悬停颜色 */
                }

        .selected-users .add-user-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background-color: #52c41a; /* 添加按钮背景色 */
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease; /* 动画效果 */
        }

            .selected-users .add-user-btn:hover {
                background-color: #389e0d; /* 添加按钮悬停颜色 */
            }
</style> 
<div id="apibox" class="card">
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form id="frmSearch" onsubmit="return false;">
            <div class="form-group">
                <div class="row">
                    <div class="col-md-3">
                        <input class="form-control" type="text" id="txtPermissionName" placeholder="权限名称">
                    </div>
                    <div class="col-md-3"> 
                        <select class="form-control"  id="ddlUserName">
                            <option value="">请选择用户</option>
                            <option v-for="user in users" :key="user" :value="user">{{ user }}</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button @click="onSearch()" id="btnSearch" class="btn btn-secondary"><i class="mdi mdi-magnify"></i> 搜索</button>
                        <button onclick="frmSearch.reset()" class="btn btn-close m-l-15" type="submit">清空</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 工具栏 -->
    <div class="card-toolbar clearfix">
        <div class="toolbar-btn-action">
            <a class="btn btn-primary m-r-5" @click="openAdd()" href="#!"><i class="mdi mdi-plus"></i> 新增权限</a>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="card-body">
        <div class="table-responsive">
            <div class="master-table-container">
                <table class="table table-bordered">
                    <thead>
                        <tr v-if="data && data.Columns && data.Columns.length > 0">
                            <th class="width30">
                                <label class="lyear-checkbox checkbox-primary">
                                    <input type="checkbox" @change="selectAll" id="check-all"><span></span>
                                </label>
                            </th>
                            <th v-for="column in data.Columns">{{ column.ColumnDescription }}</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody v-if="data && data.Data">
                        <tr v-for="item in data.Data">
                            <td>
                                <label class="lyear-checkbox checkbox-primary">
                                    <input type="checkbox" v-model="selectedItems" :value="item.Id"><span></span>
                                </label>
                            </td>
                            <td v-for="column in data.Columns">
                                {{ item[column.PropertyName] }}
                            </td>
                            <td>
                                <button @click="openEdit(item)" class="btn btn-link"><i class="mdi mdi-lead-pencil"></i> 修改</button>
                                <button @click="deleteItem(item)" class="btn btn-link"><i class="mdi mdi-delete"></i> 删除</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 分页 -->
    @@page_control.html

    <!-- 编辑/新增模态框 -->
    <div id="modalEdit" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog  width1000 " role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">{{ modalTitle }}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label for="permissionName">权限名称</label>
                            <input type="text"   v-model="formData.Name" class="form-control" placeholder="请输入权限名称">
                        </div>
                        <div class="form-group">
                            <label for="description">描述</label>
                            <input id="description" v-model="formData.EasyDescription" class="form-control" placeholder="请输入描述" />
                            <input  v-model="formData.Id" type="hidden" />
                        </div>
                        <!-- Users 多选下拉框 -->
                        <div class="form-group">
                            <label>选择用户</label>
                            <div class="selected-users">
                                <!-- 循环显示已选用户 -->
                                <span v-if="users.length > 0&& users[0]" v-for="(user, index) in formData.Users" :key="index" class="user-badge">
                                    {{ user }}
                                    <button type="button" class="btn btn-sm btn-danger" @click="removeUser(index)">-</button>
                                </span>
                                <!-- 添加用户按钮 -->
                                <button v-if="users.length > 0&& users[0]" type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addUserModal">+</button>
                                <div v-else class="alert alert-warning">
                                    JWT的信息没有配置完整，不能加载下拉列表
                                    {{bizUserErrorMessage}}
                                </div>
                            </div>
                        </div>
                        <!-- 权限接口选项 -->
                        <div class="form-group">
                            <label>授权</label>
                        </div>
                        <div id="divGroupedItems" class="form-group"> 
                            <div>
                                <!-- 总的 CheckBox -->
                                <label>
                                    <input type="checkbox" v-model="cbGroupedItemsRooot" @change="toggleAllGroups"> 全选
                                </label>
                            </div>
                            <div v-for="(group, typeName) in groupedItems" :key="typeName" class="permission-group">
                                <!-- 分组 CheckBox -->
                                <label>
                                    <input type="checkbox" :checked="isGroupChecked(typeName)" @change="toggleGroup(typeName)">{{ typeName }}</span>
                                </label>
                                <div class="permission-items">
                                    <label v-for="item in group" :key="item.ZeroInterfaceList.Id">
                                        <input type="checkbox" v-model="selectedItems" :value="item.ZeroInterfaceList.Id"> <span style="font-weight:100">{{ item.ZeroInterfaceList.Name }}</span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="saveData()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog border3CCC width350" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">选择用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="userSelect">用户列表</label>
                        <select id="userSelect" class="form-control" v-model="selectedUser">
                            <option v-for="user in users" :value="user">{{ user }}</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="confirmAddUser">添加</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var vueObj = new Vue({
        el: '#apibox',
        data: {
            data: null,
            selectedItems: [],
            cbGroupedItemsRooot: false,
            users: [], // 用户列表
            groupedItems: [],
            bizUserErrorMessage:"",
            formData: {
                Id: 0,
                PermissionName: '',
                Description: '',
                Items: [],
                Users: []
            },
            modalTitle: '',
            isEdit: false,
            selectedUser: null // 当前选中的用户
        },
        mounted() {
            this.fetchData();
        },
        methods: {
            // 获取数据
            fetchData: function () {
                this.fetchUsers();
                this.fetchPermissionPageList();
            },
            // 搜索
            onSearch: function () {
                var url = "/PrivateReZeroRoute/100003/GetPermissionList?PermissionName=" + encodeURIComponent(document.getElementById('txtPermissionName').value) + "&userName=" + ddlUserName.value;
                axios.get(url, jwHeader)
                    .then(response => {
                        this.data = response.data;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            // 打开新增模态框
            openAdd: function () {
                this.isEdit = false;
                this.modalTitle = "新增权限";
                this.fetchPermissionItems(0);
                $('#modalEdit').modal('show');
            },
            // 打开编辑模态框
            openEdit: function (item) {
                this.isEdit = true;
                this.modalTitle = "编辑权限";
                this.fetchPermissionItems(item.Id);
                $('#modalEdit').modal('show');
            },
            // 保存数据
            saveData: function () { 
                // 遍历 formData.Items，更新 Checked 值
                if (this.formData.Items && this.formData.Items.length > 0) {
                    this.formData.Items.forEach(item => {
                        if (item.ZeroInterfaceList && this.selectedItems.includes(item.ZeroInterfaceList.Id)) {
                            item.Checked = true; // 如果在 selectedItems 中，设置为 true
                        } else {
                            item.Checked = false; // 如果不在 selectedItems 中，设置为 false
                        }
                    });
                }
                var url = this.isEdit ? "/PrivateReZeroRoute/100003/UpdatePermission" : "/PrivateReZeroRoute/100003/AddPermission";
                axios.post(url, this.formData, jwHeader)
                    .then(response => {
                        if (response.data == true) {
                            $('#modalEdit').modal('hide');
                            this.error = null;
                            this.onSearch();
                        } else {
                            tools.alert(response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            // 删除数据
            deleteItem: function (item) {
                if (confirm("确定要删除该权限吗？")) {
                    var url = "/PrivateReZeroRoute/100003/DeletePermission?Id=" + item.Id;
                    axios.get(url, jwHeader)
                        .then(response => {
                            if (response.data) {
                                this.fetchData();
                            } else {
                                alert("删除失败");
                            }
                        })
                        .catch(error => {
                            console.error(error);
                        });
                }
            },
            // 全选/取消全选
            selectAll: function (event) {
                if (event.target.checked) {
                    this.selectedItems = this.data.Data.map(item => item.Id);
                } else {
                    this.selectedItems = [];
                }
            },
            // 加载权限列表
            fetchPermissionPageList: function () {
                var url = "/PrivateReZeroRoute/100003/GetPermissionList";
                axios.get(url, jwHeader)
                    .then(response => {
                        this.data = response.data;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            // 获取用户列表
            fetchUsers: function () {
                var url = "/PrivateReZeroRoute/100003/GetBizUsers";
                axios.get(url, jwHeader)
                    .then(response => {
                        if (Array.isArray(response.data)) {
                            this.users = response.data;
                        } else if (response.data.message) {
                            this.bizUserErrorMessage = response.data.message;
                            this.users = [""];
                        }
                    })
                    .catch(error => {
                        console.error("获取用户列表失败", error);
                    });
            },
            // 获取权限接口选项
            fetchPermissionItems: function (id) {
                var url = "/PrivateReZeroRoute/100003/GetSavePermissionModelById?id=" + id;
                axios.get(url, jwHeader)
                    .then(response => {
                        this.formData = response.data;
                        // 遍历 formData.Items，根据 Checked 值更新 selectedItems
                        if (this.formData.Items && this.formData.Items.length > 0) {
                            this.selectedItems = this.formData.Items
                                .filter(item => item.Checked && item.ZeroInterfaceList) // 筛选出 Checked 为 true 的项
                                .map(item => item.ZeroInterfaceList.Id); // 获取对应的 ID
                        }
                        this.groupItemsByTypeName();
                    })
                    .catch(error => {
                        console.error("获取权限接口选项失败", error);
                    });
            },
            // 按 TypeName 分组权限接口选项
            groupItemsByTypeName: function () {
                this.groupedItems = this.formData.Items.reduce((groups, item) => {
                    const typeName = item.TypeName || "未分类";
                    if (!groups[typeName]) {
                        groups[typeName] = [];
                    }
                    groups[typeName].push(item);
                    return groups;
                }, {});
            },
            // 切换总的全选状态
            toggleAllGroups: function () {
                if (this.cbGroupedItemsRooot) {
                    this.selectedItems = this.formData.Items.map(item => item.ZeroInterfaceList.Id);
                } else {
                    this.selectedItems = [];
                }
            },
            // 检查分组是否全选
            isGroupChecked: function (typeName) {
                const group = this.groupedItems[typeName];
                return group.every(item => this.selectedItems.includes(item.ZeroInterfaceList.Id));
            },
            // 切换分组全选状态
            toggleGroup: function (typeName) {
                const group = this.groupedItems[typeName];
                const groupIds = group.map(item => item.ZeroInterfaceList.Id);
                const isChecked = this.isGroupChecked(typeName);

                if (isChecked) {
                    // 如果分组已全选，则取消选中
                    this.selectedItems = this.selectedItems.filter(id => !groupIds.includes(id));
                } else {
                    // 如果分组未全选，则选中所有
                    this.selectedItems = [...new Set([...this.selectedItems, ...groupIds])];
                }
            },
            // 添加用户
            confirmAddUser: function () { 
                if (this.selectedUser && !this.formData.Users.includes(this.selectedUser)) {
                    this.formData.Users.push(this.selectedUser);
                    $('#addUserModal').modal('hide'); // 关闭模态框
                } else if (this.formData.Users.includes(this.selectedUser)) {
                    tools.alert("用户已存在！");
                }
            },
            // 删除用户
            removeUser: function (index) {
                this.formData.Users.splice(index, 1);
            }
        }
    });
</script>
